<template>
  <el-container class="main_con">
    <ufrom @submit="saveData" ref="ufrom">

      <el-form ref="formRules" :model="myform" label-width="100px" class="form_box" :rules="formRules">
        <div class="setting_body_item">
          <div class="header">基本信息</div>
          <div class="conetnt edit_con">
            <div class="edit_content">
              <el-form-item label="活动名称" prop="title"><el-input v-model="myform.title" size="small" style="width:350px"></el-input></el-form-item>
              <el-form-item label="活动期限" prop="times" v-if="!isEdit">
                <el-date-picker
                  size="small"
                  style="width:350px"
                  v-model="myform.times"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd HH:mm"
                ></el-date-picker>
              </el-form-item>
              <el-form-item label="活动期限" v-else prop='end_time'>
                <el-date-picker size="small" disabled v-model="myform.start_time" type="datetime" placeholder="开始日期" value-format="yyyy-MM-dd HH:mm"></el-date-picker>
                <span style="margin: 0 10px;">至</span>
                <el-date-picker size="small" v-model="myform.end_time" type="datetime" placeholder="结束日期" value-format="yyyy-MM-dd HH:mm"></el-date-picker>
              </el-form-item>
              <el-form-item label="活动渠道" prop="client_type">
                <el-checkbox-group v-model="myform.client_type">
                  <el-checkbox v-entry="1" :label="'1'">微信小程序</el-checkbox>
                  <el-checkbox v-entry="2" :label="'2'">微信公众号</el-checkbox>
                  <el-checkbox v-entry="3" :label="'3'">H5</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </div>
          </div>
        </div>
        <div class="setting_body_item">
          <div class="header">规则设置</div>
          <div class="conetnt edit_con">
            <div class="edit_content">
              <el-tabs type="card" @tab-remove="delrules" v-model="TabsValue">
                <el-tab-pane :closable="i > 0" :key="i" v-for="(item, i) in myform.rules" :label="'规则' + (i + 1)" :name="i + ''">
                  <template slot="title">
                    <div>
                      <i class="el-icon-error u-m-r-20" v-if="i > 0" @click.stop="delrules(i)"></i>
                      <span>规则{{ i + 1 }}</span>
                    </div>
                  </template>
                  <el-form-item label="单笔充值满"><el-input size="small" v-model="item.single_recharge" style="width:200px"></el-input></el-form-item>
                  <el-form-item label="奖励内容">
                    <el-checkbox-group v-model="item.rewards_type">
                      <el-checkbox :label="1">优惠券</el-checkbox>
                      <el-checkbox :label="2">积分</el-checkbox>
                      <el-checkbox :label="3">余额</el-checkbox>
                    </el-checkbox-group>

                    <div class="box" v-if="item.rewards_type.length > 0">
                      <el-form-item v-if="item.rewards_type.indexOf(1) > -1" label="优惠券">
                        <el-button @click="selectConpon(i)">添加优惠卷（{{ item.coupon.length }}/3）</el-button>
                        <el-table class="mt_15" :data="item.coupon">
                          <el-table-column label="优惠券名称" prop="name"></el-table-column>
                          <el-table-column prop="conditions" label="满" width="180"></el-table-column>
                          <el-table-column prop="denomination" label="减" width="180"></el-table-column>
                         <!-- <el-table-column prop="total_limit" label="库存"></el-table-column> -->
                          <el-table-column label="操作">
                            <template slot-scope="scope">
                              <el-button type="text" @click="deleteData(i, scope.row.id)">删除</el-button>
                            </template>
                          </el-table-column>
                        </el-table>
                      </el-form-item>
                      <el-form-item v-if="item.rewards_type.indexOf(2) > -1" label="积分"><el-input size="small" v-model="item.credit" style="width: 300px;"></el-input></el-form-item>
                      <el-form-item v-if="item.rewards_type.indexOf(3) > -1" label="余额"><el-input size="small" v-model="item.balance" style="width: 300px;"></el-input></el-form-item>
                    </div>
                  </el-form-item>
                </el-tab-pane>
              </el-tabs>
              <div class="btns_div" v-if="myform.rules.length < 10"><el-button @click="addrules">添加规则</el-button></div>
            </div>
          </div>
        </div>
      </el-form>
    </ufrom>
    <el-dialog title="选择优惠券" :visible.sync="showSelectCon" width="50%" append-to-body destroy-on-close>
      <SelectConpon ref="SelectConpon" :limit="3" :key="rk" :data="selectCon" @outData="closePro"></SelectConpon>
    </el-dialog>
  </el-container>
</template>

<script>
import {addrecharge, getrecharge, editrecharge} from '@/api/mall/recharge';
import {getPro} from '@/api/shop/product';
import SelectConpon from '@/components/SelectConpon/index';

import {jur_addons_item, jur_addons} from '@/utils/jurisdiction';
export default {
  data() {
    var checkstock = (rule, value, callback) => {
      console.log(rule);
      let a = rule.field;
      let c = a.replace(/Prolist./g, '');
      let d = c.split('.');
      let id = Number(d[0]);
      value = Number(value);
      if (!value) {
        return callback(new Error('不能为空'));
      }
      setTimeout(() => {
        let stock = this.myform.Prolist[id].total - this.myform.Prolist[id].sell;
        if (stock < value) {
          callback(new Error('活动库存不能大于实际库存'));
        } else {
          callback();
        }
      }, 1000);
    };
    var checkprice = (rule, value, callback) => {
      console.log(rule);
      let a = rule.field;
      let c = a.replace(/Prolist./g, '');
      let d = c.split('.');
      let id = Number(d[0]);
      value = Number(value);
      if (!value) {
        return callback(new Error('不能为空'));
      }
      setTimeout(() => {
        let sell_price = this.myform.Prolist[id].sell_price;
        if (sell_price < value) {
          callback(new Error('活动价格不能大于售卖价格'));
        } else {
          callback();
        }
      }, 1000);
    };
    return {
      rk: 0,
      prize_index: '0',
      prize_time: '',
      id: '',

      source: [],
      selectPro: [],
      myform: {
        title: '', //,	必填	string	名字
        start_time: '', //,	必填	date	开始时间
        end_time: '', //,	必填	date	结束时间
        client_type: [], //,	多选	string	来源（逗号分隔）1微信公众号2小程序3h5
        rules: [
          {
            single_recharge: '',
            rewards_type: [],
            balance: '',
            coupon: [],
            credit: '',
            couponlist: []
          }
        ]
      },
      activeNames: ['1'],

      form: {
        title: '', //,	必填	string	名字
        start_time: '', //,	必填	date	开始时间
        end_time: '', //,	必填	date	结束时间
        client_type: '', //,	多选	string	来源（逗号分隔）1微信公众号2小程序3h5
        rules: {
          use_agent: 0, //,	必填	int	0分销
          limit_type: [0, 0, 0], //,必填	string	{0,0,0}限购次数 {选项，活动期内每人最多购买, 活动期内每人每天最多购买}
          is_show: 0 //,
        } //,	必填	string	规则设置
      },
      formRules: {
        title: [
          {
            required: true,
            message: '请输入活动名称',
            trigger: 'blur'
          }
        ],
        times: [
          {
            required: true,
            message: '请选择活动时间',
            trigger: 'change'
          }
        ],
        end_time: [
          {
            required: true,
            message: '请选择活动结束时间',
            trigger: 'change'
          }
        ],
        client_type: [
          {
            required: true,
            message: '请至少选择一个活动渠道',
            trigger: 'change'
          }
        ],

        is_show_time: [
          {
            required: true,
            message: '请选择预热时间',
            trigger: 'blur'
          }
        ],
        activity_stock: [
          {
            validator: checkstock,
            trigger: ['blur', 'change']
          }
        ],
        activity_price: [
          {
            validator: checkprice,
            trigger: ['blur', 'change']
          }
        ]
      },
      showSelectCon: false,
      selectCon: [],
      isEdit: false,
      TabsValue: ''
    };
  },
  created() {
    if (this.$route.query.id) {
      //编辑状态
      this.isEdit = true;
      this.id = this.$route.query.id;
      this.getdetail();
    }
  },
  components: {
    SelectConpon
  },
  methods: {
    selectConpon(i) {
      this.index = i;
      this.selectCon = this.myform.rules[i].coupon;
      this.showSelectCon = true;
      this.$nextTick(() => {
        this.$refs.SelectConpon.init();
      });
    },
    //关闭选择产品框
    closePro(list) {
      if (list) {
        this.myform.rules[this.index].coupon = list;
      }

      this.showSelectCon = false;
    },
    addrules() {
      this.myform.rules.push({
        single_recharge: '',
        rewards_type: [],
        balance: '',
        coupon: [],
        credit: '',
        couponlist: []
      });
    },
    delrules(i) {
      if (i == this.TabsValue) {
        this.TabsValue = this.TabsValue - 1 + '';
      }
      this.myform.rules.splice(i, 1);
    },
    getdetail() {
      let data = {
        id: this.id
      };
      getrecharge(data).then(res => {
        let json = res.msg;
        this.myform.title = json.title;
        this.myform.client_type = json.client_type.split(',');
        this.myform.start_time = json.start_time;
        this.myform.end_time = json.end_time;
        this.myform.times = [json.start_time, json.end_time];
        // this.myform.rewards_type=JSON.parse(json.rewards_type)
        // let rules = JSON.parse(json.rules);
        let recharge = json.recharge;
        let rules = [];
        recharge.forEach(a => {
          rules.push({
            single_recharge: a.single_recharge,
            rewards_type: JSON.parse(a.rewards_type),
            balance: a.balance,
            coupon: a.coupon,
            couponlist: a.couponlist,
            credit: a.credit,
            id: a.id,
            aid: a.aid
          });
        });
        this.myform.rules = rules;
      });
    },
    deleteData(i, id) {
      let n = this.myform.rules[i].coupon.findIndex(_ => _.id == id);
      this.myform.rules[i].coupon.splice(n, 1);
    },
    // 添加抽奖 && 修改
    saveData() {
      let _this = this; 
      this.$refs['formRules'].validate(valid => {
        if (valid) {
          _this.save();
        }else{
          _this.$refs.ufrom.init();
        }
      });
    },
    save() {
      let obj = {
        title: this.myform.title,
        start_time: this.myform.times[0],
        end_time: this.myform.times[1],
        type: this.myform.type,
        client_type: this.myform.client_type.join(',')
        // rules: this.myform.rules
      };
      let rules = JSON.parse(JSON.stringify(this.myform.rules));
      rules.forEach(a => {
        let coupon = [];
        a.coupon.forEach(c => {
          coupon.push(c.id);
        });
        a.coupon = coupon;
      });
      obj.rules = rules;
      if (this.id) {
        obj.id = this.id;
        editrecharge(obj).then(res => {
          this.$refs.ufrom.init();
          this.$router.push({
            path: '/recharge/index'
          });
        }).catch(e=>{
          this.$refs.ufrom.init();
        });
      } else {
        addrecharge(obj).then(res => {
        this.$refs.ufrom.init();
          this.$router.push({
            path: '/recharge/index'
          });
        }).catch(e=>{
          this.$refs.ufrom.init();
        });
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.main_con {
  height: 100%;
  .gift_body {
    background-color: #ffffff;
    padding: 20px 30px;
    // display: flex;
    // height: 100%;
    .box {
      margin-top: 10px;
      background-color: #f4f6f8;
      border-radius: 2px;
      font-size: 14px;
      line-height: 20px;
      color: #262b30;
      padding: 20px;
    }
    .right {
      flex: 1;
      margin-left: 30px;
      padding: 20px;
      border-radius: 15px;
      box-sizing: border-box;
      box-shadow: 0px 5px 10px #e8e8e8;
      overflow: auto;
      height: 100%;
      .form_box {
        /deep/.el-tabs--left .el-tabs__header.is-left {
          height: 67vh;
        }
        .prize_img {
          width: 120px;
          height: 120px;
        }
        .block {
          width: 400px;
        }
        .box_ove {
          height: 68vh;
          overflow: auto;
        }
      }
      .form_button {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-top: 15px;
        .el-button {
          width: 200px;
        }
      }
    }
    .left {
      .app_div {
        width: 410px;
        height: 785px;
        padding: 62px 28px 90px 27px;
        position: relative;
        background: url('~@/assets/images/ipbg.png') no-repeat;
        background-size: 100%;
        overflow: hidden;
        .app_main {
          overflow: scroll;
          height: 100%;
          z-index: 2;
          position: relative;
          background: #fff;
          &::-webkit-scrollbar {
            display: none; /* Chrome Safari */
          }
        }
        .div_bg {
          position: absolute;
          width: 100%;
          height: 100%;
          overflow: hidden;
          .phone-title {
            height: 64px;
            background: #fff;
            background-size: 100% auto;
            text-align: center;
            cursor: pointer;
            display: block;
            white-space: nowrap;
            text-overflow: ellipsis;
            position: relative;
            width: 100%;
            &.pageInfo {
              box-shadow: 0 0 2px 0 #2d8cf0;
              z-index: 1000;
              position: relative;
            }
            .page-title {
              position: absolute;
              z-index: 100;
              font-family: PingFang SC;
              font-style: normal;
              font-weight: 600;
              font-size: 18px;
              line-height: 25px;
              display: flex;
              align-items: center;
              text-align: center;
              color: #212121;
              left: 50%;
              transform: translate(-50%, 0);
              bottom: 10px;
              margin: 0;
            }

            .phone-top {
              display: flex;
              flex-direction: column;
              width: 100%;
              overflow: hidden;

              .custom-navbar img {
                position: absolute;
                right: 7px;
                width: 87px;
                height: 32px;
                bottom: 6px;
              }
            }
          }
          .bg_img {
            width: 100%;
            display: block;
            position: absolute;
            left: 50%;
            transform: translateX(-50%);
          }
        }
        .div_content {
          width: 100%;
          // height: 100%;
          position: relative;
          z-index: 2;
          .content_box {
            width: 290px;
            // margin-top: 300px;
            margin-left: auto;
            margin-right: auto;
            margin-bottom: 0px;
            .content_bg {
              width: 100%;
              height: 280px;
              background-image: linear-gradient(#ff9c6b, #ff5c4a);
              border-radius: 15px;
              box-sizing: border-box;
              padding: 10px 11px 38px;
              box-shadow: 0px 3px 0px #d72b27 inset;
              border-left: solid 2px rgba(255, 255, 255, 0.4);
              border-right: solid 2px rgba(255, 255, 255, 0.4);
              .content_txt {
                font-size: 12px;
                text-align: center;
                color: #fff;
              }
              .content_bg1 {
                width: 100%;
                height: 100%;
                background: #ff4631;
                border-radius: 15px;
                box-shadow: rgba(255, 255, 255, 0.3) 0px 1px 5px;
                padding: 10px;
                .content_bg2 {
                  width: 100%;
                  height: 100%;
                  background: #d62e1e;
                  border-radius: 15px;
                  box-shadow: #d02a1b 0px -3px 5px;
                  .lottery-box {
                    overflow: hidden;
                  }
                  .lottery {
                    width: 100%;
                    height: 100%;
                  }
                  .lottery .lottery-item {
                    height: 100%;
                    position: relative;
                  }

                  .lottery .lottery-item ul li {
                    width: 30%;
                    height: 30%;
                    position: absolute;
                    margin: 5px;
                    list-style-type: none;
                  }

                  .lottery .lottery-item ul li:nth-child(2) {
                    left: 33%;
                  }

                  .lottery .lottery-item ul li:nth-child(3) {
                    left: 66%;
                  }

                  .lottery .lottery-item ul li:nth-child(4) {
                    left: 66%;
                    top: 32%;
                  }

                  .lottery .lottery-item ul li:nth-child(5) {
                    left: 66%;
                    top: 64%;
                  }

                  .lottery .lottery-item ul li:nth-child(6) {
                    left: 33%;
                    top: 64%;
                  }

                  .lottery .lottery-item ul li:nth-child(7) {
                    left: 0;
                    top: 64%;
                  }

                  .lottery .lottery-item ul li:nth-child(8) {
                    left: 0;
                    top: 32%;
                  }

                  .lottery .lottery-item ul li .box {
                    height: 100%;
                    position: relative;
                    text-align: center;
                    background-color: #fff;
                    box-shadow: 0px -7px 0px #ffcacb inset;
                    border-radius: 12px;
                    overflow: hidden;
                    margin: 0;
                    padding: 5px;
                    p {
                      font-size: 12px;
                      margin-top: 4px;
                      text-align: center;
                      line-height: 10px;
                    }
                  }

                  .lottery .lottery-item ul li .box img {
                    display: block;
                    height: 30px;
                    margin: 0 auto;
                  }

                  .lottery .lottery-item ul li.on .box {
                    border: #ffb000 solid 2px;
                    border-bottom: none;
                    box-shadow: 0px -7px 0px #ffb000 inset;
                  }

                  .lottery .lottery-item .lottery-start {
                    position: absolute;
                    width: 30%;
                    height: 30%;
                    margin: 5px;
                    left: 48%;
                    top: 48%;
                    transform: translate(-50%, -50%);
                    img {
                      width: 100%;
                      display: block;
                    }
                  }
                }
              }
            }
            .bg_box {
              width: 72%;
              margin: auto;
              height: 30px;
              background: #f9604f;
              border: #fa5542 solid 3px;
              display: block;
              position: relative;
              top: -28px;
              z-index: -1;
              font-size: 30px;
              border-radius: 5px;
              transform: perspective(0.6em) rotateX(20deg);
            }
            .bg_imgr {
              position: absolute;
              z-index: 9;
              width: 100%;
              bottom: 0px;
            }
          }
        }
      }
    }
  }
}
.product-item {
  display: flex;
  align-items: center;

  img {
    width: 40px;
    height: 40px;
    margin-right: 10px;
  }
}
.aaa {
  position: relative;
  height: 1px;
}
.setting_body_item {
  .header {
    background: #e0e3e8;
    height: 40px;
    line-height: 40px;
    padding-left: 20px;
    margin-top: 20px;
  }
  .btns_div {
    margin: 20px 0;
    text-align: center;
  }
}

.setting_bootom {
  height: 60px;
  line-height: 60px;
  border-top: 1px solid #dcdfe6;
}
.proImg {
  display: flex;
  align-items: center;
}

.pro_t0 {
  color: #2d8cf0;
  background: #f0faff;
  border-radius: 5px;
  padding: 0 3px;
  margin-right: 5px;
}

.pro_t1 {
  color: #e6a23c;
  background: #d2efe0;
  border-radius: 5px;
  padding: 0 3px;
  margin-right: 5px;
}
.tips {
  color: #939799;
  margin: 10px 0;
  font-size: 12px;
}
.ladder_num {
  width: 350px;
  border: 1px solid #e9edef;

  .name {
    width: 100px;
  }
  .num {
    width: 180px;
  }
  .btns_div {
    width: 70px;
  }
  .ladder_num_header,
  .content_item {
    display: flex;
    align-items: center;
    text-align: center;
  }
  .ladder_num_header {
    background: #f4f6f8;
    font-weight: bold;
  }
  .content_item {
    border-top: 1px solid #e9edef;
    justify-content: center;
    .num {
      display: flex;
      align-items: center;
      padding: 20px 0 0 0;
    }
  }
}
</style>
